package example.servlet;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import example.model.App;
import example.model.User;

public class LoginServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        // We let the LoginServlet's init method create the global
        // "app" object.
        getServletContext().setAttribute("app", new App());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        showForm(req, res);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        App app = (App)getServletContext().getAttribute("app");

        String name = req.getParameter("name");
        String password = req.getParameter("password");

        String message = null;

        try {
            if (name != null && password != null) {
                User user = app.login(name, password);

                if (user != null) {
                    req.getSession().setAttribute("user", user);
                    res.sendRedirect(
                        res.encodeRedirectURL("feed.jxt"));
                    return;
                }
            }
        } catch (IllegalArgumentException e) {
            message = e.getMessage();
        }

        req.setAttribute("message", message);
        showForm(req, res);
    }

    void showForm(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        getServletContext()
            .getRequestDispatcher("/WEB-INF/jxt/login.jxt")
            .include(req, res);
    }
}